/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package program.bl;

import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;
import program.beans.Bill;
import program.database.Database;
import program.utilities.DateUtilities;

/**
 * Controller-class for bills, which are stored in the database. Implemented in
 * singleton
 *
 * Responsible: Bernhard
 */
public class BillController {

    private static BillController instance;
    private ArrayList<Bill> bills = new ArrayList<>();
    private Database db = Database.getDatabase();

    private BillController() {
        try {
            bills.addAll(db.getBills(new java.sql.Date(DateUtilities.getMonthBegin().getTime()),
                    new java.sql.Date(DateUtilities.getMonthEnd().getTime())));
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex);

        }
    }

    public static BillController getInstance() {
        if (instance == null) {
            instance = new BillController();
        }

        return instance;
    }

    public ArrayList<Bill> getBills() throws Exception {
        return bills;
    }

    public ArrayList<Bill> getBills(Date from, Date since) throws Exception {
        bills.clear();
        bills.addAll(db.getBills(new java.sql.Date(from.getTime()),
                new java.sql.Date(since.getTime())));
        return bills;
    }

    public void updateList(Date from, Date since) throws Exception {
        bills.clear();
        bills.addAll(db.getBills(new java.sql.Date(from.getTime()),
                new java.sql.Date(since.getTime())));

    }

    public void deleteBill(Bill b) throws Exception {
        db.deleteBill(b);
        bills.remove(b);
    }

    public void addBill(Bill b) throws Exception {
        db.addBill(b);
        bills.add(0, b);
    }

    public Bill getBill(int i) {
        return bills.get(i);
    }

    public void editBill(int index, Bill newBill) throws Exception {
        db.editBill(newBill);
        bills.remove(index);
        bills.add(index, newBill);
    }

    public int getSize() {
        return bills.size();
    }
}